package com.goods.controller.business;


import com.goods.common.model.business.Consumer;
import com.goods.common.response.ResponseBean;
import com.goods.common.utils.ListPageUtils;
import com.goods.common.vo.business.ConsumerVO;
import com.goods.service.ConsumerService;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/business/consumer")
public class ConsumerController {

    @Autowired
    ConsumerService consumerService;

    @GetMapping("/findConsumerList")
    public ResponseBean findConsumerList(Integer pageNum, Integer pageSize, String name, String address, String contact){
        Map map = new HashMap();
        List<Consumer> consumers = consumerService.findConsumerList(name,address,contact);
        List<Consumer> page = ListPageUtils.page(consumers, pageSize, pageNum);
        map.put("total",consumers.size());
        map.put("rows",page);
        return ResponseBean.success(map);
    }

    @PostMapping("/add")
    public ResponseBean add(@RequestBody ConsumerVO consumerVO){
        int i = consumerService.add(consumerVO);
        if (i == 0){
            return ResponseBean.error("添加失败");
        }else {
            return ResponseBean.success();
        }
    }

    @GetMapping("/edit/{id}")
    public ResponseBean edit(@PathVariable Long id){
        Consumer consumer = consumerService.edit(id);
        ConsumerVO consumerVO = new ConsumerVO();
        BeanUtils.copyProperties(consumer,consumerVO);
        return ResponseBean.success(consumerVO);
    }

    @PutMapping("/update/{id}")
    public ResponseBean update(@PathVariable Long id,@RequestBody ConsumerVO consumerVO){
        int i = consumerService.update(id,consumerVO);
        if (i == 0){
            return ResponseBean.error("修改失败");
        }else {
            return ResponseBean.success();
        }
    }

    @DeleteMapping("/delete/{id}")
    public ResponseBean delete(@PathVariable Long id){
        int i = consumerService.delete(id);
        if (i == 0){
            return ResponseBean.error("删除失败");
        }else {
            return ResponseBean.success();
        }
    }

    @GetMapping("/findAll")
    public ResponseBean findAll(){
        List<Consumer> consumers = consumerService.findAll();
        List<ConsumerVO> collect = consumers.stream().map(consumer -> {
            ConsumerVO consumerVO = new ConsumerVO();
            BeanUtils.copyProperties(consumer, consumerVO);
            return consumerVO;
        }).collect(Collectors.toList());
        return ResponseBean.success(collect);
    }
}
